// 全局变量
let currentUser = null;
let currentCategory = null;
let minPrice = null;
let maxPrice = null;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    checkLoginStatus();
    loadCategories();
    loadProducts();
});

// 检查登录状态
function checkLoginStatus() {
    const token = localStorage.getItem('token');
    if (token) {
        currentUser = JSON.parse(localStorage.getItem('user'));
        updateUserUI();
    }
}

// 更新用户界面
function updateUserUI() {
    const userActions = document.getElementById('userActions');
    if (currentUser) {
        userActions.innerHTML = `
            <span class="text-light me-3">欢迎, ${currentUser.username}</span>
            <button class="btn btn-outline-light" onclick="logout()">退出</button>
        `;
    } else {
        userActions.innerHTML = `
            <a href="/login.html" class="btn btn-outline-light me-2">登录</a>
            <a href="/register.html" class="btn btn-primary">注册</a>
        `;
    }
}

// 加载商品分类
async function loadCategories() {
    try {
        const response = await fetch('/api/products/categories');
        const categories = await response.json();
        const categoryList = document.getElementById('categoryList');
        
        // 添加"全部"选项
        categoryList.innerHTML = `
            <a href="#" class="list-group-item list-group-item-action category-item active" 
               onclick="filterByCategory(null)">全部商品</a>
        `;
        
        // 添加分类选项
        categories.forEach(category => {
            categoryList.innerHTML += `
                <a href="#" class="list-group-item list-group-item-action category-item" 
                   onclick="filterByCategory('${category}')">${category}</a>
            `;
        });
    } catch (error) {
        console.error('加载分类失败:', error);
    }
}

// 加载商品列表
async function loadProducts() {
    try {
        let url = '/api/products';
        if (currentCategory) {
            url += `?category=${currentCategory}`;
        }
        if (minPrice !== null) {
            url += `${url.includes('?') ? '&' : '?'}minPrice=${minPrice}`;
        }
        if (maxPrice !== null) {
            url += `${url.includes('?') ? '&' : '?'}maxPrice=${maxPrice}`;
        }

        const response = await fetch(url);
        const products = await response.json();
        displayProducts(products);
    } catch (error) {
        console.error('加载商品失败:', error);
    }
}

// 显示商品列表
function displayProducts(products) {
    const productList = document.getElementById('productList');
    productList.innerHTML = '';

    products.forEach(product => {
        const col = document.createElement('div');
        col.className = 'col-md-4 col-sm-6';
        col.innerHTML = `
            <div class="card product-card">
                <img src="${product.image_url || 'images/default-product.jpg'}" 
                     class="card-img-top product-image" alt="${product.name}">
                <div class="card-body">
                    <h5 class="card-title product-title">${product.name}</h5>
                    <p class="card-text product-description">${product.description}</p>
                    <div class="d-flex justify-content-between align-items-center">
                        <span class="product-price">¥${product.price}</span>
                        <button class="btn btn-primary" onclick="addToCart(${product.id})">
                            加入购物车
                        </button>
                    </div>
                </div>
            </div>
        `;
        productList.appendChild(col);
    });
}

// 按分类筛选商品
function filterByCategory(category) {
    currentCategory = category;
    document.querySelectorAll('.category-item').forEach(item => {
        item.classList.remove('active');
    });
    event.target.classList.add('active');
    loadProducts();
}

// 按价格筛选商品
function filterByPrice() {
    minPrice = document.getElementById('minPrice').value;
    maxPrice = document.getElementById('maxPrice').value;
    loadProducts();
}

// 搜索商品
function searchProducts() {
    const searchTerm = document.getElementById('searchInput').value.toLowerCase();
    const products = document.querySelectorAll('.product-card');
    
    products.forEach(product => {
        const title = product.querySelector('.product-title').textContent.toLowerCase();
        const description = product.querySelector('.product-description').textContent.toLowerCase();
        
        if (title.includes(searchTerm) || description.includes(searchTerm)) {
            product.parentElement.style.display = '';
        } else {
            product.parentElement.style.display = 'none';
        }
    });
}

// 添加到购物车
async function addToCart(productId) {
    if (!currentUser) {
        alert('请先登录');
        window.location.href = '/login.html';
        return;
    }

    try {
        const response = await fetch('/api/cart/add', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify({ productId })
        });

        if (response.ok) {
            alert('商品已添加到购物车');
        } else {
            const error = await response.json();
            alert(error.error || '添加失败');
        }
    } catch (error) {
        console.error('添加到购物车失败:', error);
        alert('添加到购物车失败');
    }
}

// 退出登录
function logout() {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    currentUser = null;
    updateUserUI();
    window.location.href = '/';
} 